package com.example.dbsample.util.json;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.*;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * JSON 工具类
 *
 * @author 阿沐 babamu@126.com
 * <a href="https://maku.net">MAKU</a>
 */
@Slf4j
public class JsonUtils {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }
    
    public static String toJsonString(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T parseObject(String text, Class<T> clazz) {
        if (StrUtil.isEmpty(text)) {
            return null;
        }
        try {
            return objectMapper.readValue(text, clazz);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T parseObject(byte[] bytes, Class<T> clazz) {
        if (ArrayUtil.isEmpty(bytes)) {
            return null;
        }
        try {
            return objectMapper.readValue(bytes, clazz);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T parseObject(String text, TypeReference<T> typeReference) {
        try {
            return objectMapper.readValue(text, typeReference);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> List<T> parseArray(String text, Class<T> clazz) {
        if (StrUtil.isEmpty(text)) {
            return new ArrayList<>();
        }
        try {
            return objectMapper.readValue(text, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String getString(String jsonStr, String key) {
        JsonElement jsonElement = (new JsonParser()).parse(jsonStr);
        if(jsonElement != null && jsonElement.isJsonObject()) {
            JsonElement keyElement = ((JsonObject) jsonElement).get(key);
            if(keyElement != null && !keyElement.isJsonNull()) {
                return !keyElement.isJsonObject() && !keyElement.isJsonArray() ? keyElement.getAsString() : keyElement.toString();
            } else {
                return "";
            }
        } else {
            return "";
        }
    }

    public static String encodeNotSkipNull(Map<String, Object> map) {
        Gson gson = (new GsonBuilder()).serializeNulls().create();
        return gson.toJson(map);
    }

    public static String encodeObject(Object req) {
        Gson gson = (new GsonBuilder()).serializeNulls().create();
        return gson.toJson(req);
    }

    public static void main(String[] args) {
        String jsonStr = "{\"supplierId\":\"sample\",\"key\":\"value\"}";
        System.out.println("JsonUtils = " + JsonUtils.getString(jsonStr, "supplierId"));

        List<String> strList = Arrays.asList("123", "345");
        System.out.println(JsonUtils.toJsonString(strList));
    }

    /**
     * map转json字符串
     */
    public static String mapToJsonStr(Object object) {
        return JSONObject.toJSONString(object);
    }

    public static String objectToJsonStr(Object object) {
        return JSONObject.toJSONString(object);
    }

    public static Map jsonStrToMap(String jsonStr) {
        return JSONObject.parseObject(jsonStr, Map.class);
    }

    public static String toStringNotThrow(Object object) {
        String result = null;
        try {
            if(object == null) {
                return null;
            }
            result = JSON.toJSONString(object);
        } catch (Throwable e) {
            log.info("toStringNotThrow error", e);
        }
        return result;
    }
}
